<template>
  <div class="settings-page">
    <div class="settings-header">
      <h1>⚙️ 设置</h1>
      <router-link to="/" class="btn btn-secondary">返回首页</router-link>
    </div>
    
    <!-- 账户信息 -->
    <div class="settings-section">
      <h2>账户信息</h2>
      <div class="info-card">
        <div class="info-row">
          <span class="info-label">用户名</span>
          <span class="info-value">{{ authStore.user?.username }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">邮箱</span>
          <span class="info-value">{{ authStore.user?.email }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">角色</span>
          <span class="info-value">
            <span class="badge" :class="authStore.isAdmin ? 'badge-admin' : 'badge-user'">
              {{ authStore.isAdmin ? '管理员' : '普通用户' }}
            </span>
          </span>
        </div>
        <div class="info-row">
          <span class="info-label">注册时间</span>
          <span class="info-value">{{ formatDate(authStore.user?.createdAt) }}</span>
        </div>
      </div>
    </div>
    
    <!-- 修改密码 -->
    <div class="settings-section">
      <h2>修改密码</h2>
      <form @submit.prevent="handleChangePassword" class="settings-form">
        <div class="form-group">
          <label class="form-label">当前密码</label>
          <input
            v-model="passwordForm.oldPassword"
            type="password"
            class="form-input"
            placeholder="输入当前密码"
            required
          />
        </div>
        
        <div class="form-group">
          <label class="form-label">新密码</label>
          <input
            v-model="passwordForm.newPassword"
            type="password"
            class="form-input"
            placeholder="输入新密码（至少8位）"
            required
            minlength="8"
          />
        </div>
        
        <div class="form-group">
          <label class="form-label">确认新密码</label>
          <input
            v-model="passwordForm.confirmPassword"
            type="password"
            class="form-input"
            placeholder="再次输入新密码"
            required
          />
        </div>
        
        <button type="submit" class="btn btn-primary" :disabled="passwordLoading">
          {{ passwordLoading ? '处理中...' : '修改密码' }}
        </button>
        
        <p class="form-hint">
          ⚠️ 修改密码后，您将被登出所有设备，需要重新登录
        </p>
      </form>
    </div>
    
    <!-- 用户偏好 -->
    <div class="settings-section">
      <h2>用户偏好</h2>
      <form @submit.prevent="handleSavePreferences" class="settings-form">
        <div class="form-group">
          <label class="form-label">主题</label>
          <select v-model="preferencesForm.theme" class="form-select">
            <option value="auto">跟随系统</option>
            <option value="light">浅色模式</option>
            <option value="dark">深色模式</option>
          </select>
        </div>
        
        <div class="form-group">
          <label class="form-label">语言</label>
          <select v-model="preferencesForm.language" class="form-select">
            <option value="zh-CN">简体中文</option>
            <option value="en-US">English</option>
          </select>
        </div>
        
        <div class="form-group">
          <label class="form-label">默认令牌周期</label>
          <select v-model.number="preferencesForm.defaultTokenPeriod" class="form-select">
            <option :value="30">30秒</option>
            <option :value="60">60秒</option>
          </select>
        </div>
        
        <div class="form-group">
          <label class="checkbox-label">
            <input
              v-model="preferencesForm.autoCopyOnClick"
              type="checkbox"
              class="form-checkbox"
            />
            <span>点击验证码自动复制</span>
          </label>
        </div>
        
        <div class="form-group">
          <label class="checkbox-label">
            <input
              v-model="preferencesForm.showAccountName"
              type="checkbox"
              class="form-checkbox"
            />
            <span>显示账户名称</span>
          </label>
        </div>
        
        <button type="submit" class="btn btn-primary" :disabled="preferencesLoading">
          {{ preferencesLoading ? '保存中...' : '保存偏好' }}
        </button>
      </form>
    </div>
    
    <!-- 会话管理 -->
    <div class="settings-section">
      <h2>会话管理</h2>
      <p class="section-description">
        当前活跃的登录会话。您可以终止任何会话来提高账户安全性。
      </p>
      
      <div v-if="sessions.length > 0" class="sessions-list">
        <div v-for="session in sessions" :key="session.id" class="session-card">
          <div class="session-info">
            <div class="session-device">
              <strong>{{ session.deviceName || '未知设备' }}</strong>
              <span v-if="session.isCurrent" class="badge badge-success">当前会话</span>
            </div>
            <div class="session-details">
              <span>🌐 {{ session.ipAddress }}</span>
              <span>🕒 最后活动: {{ formatDate(session.lastActivity) }}</span>
            </div>
          </div>
          <button
            v-if="!session.isCurrent"
            @click="revokeSession(session.id)"
            class="btn btn-sm btn-danger"
          >
            终止
          </button>
        </div>
      </div>
      
      <button @click="loadSessions" class="btn btn-secondary">
        刷新会话列表
      </button>
    </div>
    
    <!-- 危险区域 -->
    <div class="settings-section danger-zone">
      <h2>🚨 危险操作</h2>
      <div class="danger-actions">
        <button @click="handleLogoutAll" class="btn btn-warning">
          登出所有设备
        </button>
        <!-- 可以添加删除账户等其他危险操作 -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/store/auth';
import { useUserStore } from '@/store/user';
import api from '@/api';

const router = useRouter();
const authStore = useAuthStore();
const userStore = useUserStore();

const passwordLoading = ref(false);
const preferencesLoading = ref(false);
const sessions = ref([]);

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

const preferencesForm = reactive({
  theme: 'auto',
  language: 'zh-CN',
  defaultTokenPeriod: 30,
  autoCopyOnClick: true,
  showAccountName: true,
});

function formatDate(dateString) {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
}

async function handleChangePassword() {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    alert('两次输入的新密码不一致');
    return;
  }
  
  if (passwordForm.newPassword.length < 8) {
    alert('新密码至少需要8位');
    return;
  }
  
  passwordLoading.value = true;
  
  try {
    await authStore.changePassword(passwordForm.oldPassword, passwordForm.newPassword);
    alert('密码修改成功！即将跳转到登录页面...');
    router.push('/login');
  } catch (error) {
    alert('密码修改失败: ' + (error.response?.data?.error?.message || '请检查当前密码'));
  } finally {
    passwordLoading.value = false;
  }
}

async function handleSavePreferences() {
  preferencesLoading.value = true;
  
  try {
    await userStore.updatePreferences(preferencesForm);
    alert('偏好设置已保存！');
  } catch (error) {
    alert('保存失败: ' + (error.response?.data?.error?.message || error.message));
  } finally {
    preferencesLoading.value = false;
  }
}

async function loadSessions() {
  try {
    const response = await api.get('/auth/sessions');
    sessions.value = response.data.data || [];
  } catch (error) {
    console.error('加载会话失败:', error);
  }
}

async function revokeSession(sessionId) {
  if (!confirm('确定要终止这个会话吗？')) return;
  
  try {
    await api.delete(`/auth/sessions/${sessionId}`);
    sessions.value = sessions.value.filter(s => s.id !== sessionId);
    alert('会话已终止');
  } catch (error) {
    alert('操作失败');
  }
}

async function handleLogoutAll() {
  if (!confirm('确定要登出所有设备吗？您需要重新登录。')) return;
  
  try {
    await api.post('/auth/logout-all');
    await authStore.logout();
    router.push('/login');
  } catch (error) {
    alert('操作失败');
  }
}

onMounted(async () => {
  // 加载用户偏好
  try {
    const prefs = await userStore.fetchPreferences();
    if (prefs) {
      Object.assign(preferencesForm, prefs);
    }
  } catch (error) {
    console.error('加载偏好设置失败:', error);
  }
  
  // 加载会话列表
  loadSessions();
});
</script>

<style scoped>
.settings-page {
  max-width: 900px;
  margin: 0 auto;
  padding: 40px 20px;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
}

.settings-header h1 {
  font-size: 32px;
  color: var(--text-color, #333);
}

.settings-section {
  background: var(--bg-color, #fff);
  border-radius: 12px;
  padding: 30px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.settings-section h2 {
  font-size: 20px;
  color: var(--text-color, #333);
  margin-bottom: 20px;
}

.section-description {
  color: var(--text-secondary, #6b7280);
  margin-bottom: 20px;
  line-height: 1.6;
}

.info-card {
  border: 1px solid var(--border-color, #e5e7eb);
  border-radius: 8px;
  overflow: hidden;
}

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid var(--border-color, #e5e7eb);
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  font-weight: 500;
  color: var(--text-secondary, #6b7280);
}

.info-value {
  color: var(--text-color, #333);
}

.badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 13px;
  font-weight: 500;
}

.badge-admin {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.badge-user {
  background: var(--bg-secondary, #f3f4f6);
  color: var(--text-color, #333);
}

.badge-success {
  background: #10b981;
  color: white;
}

.settings-form {
  max-width: 500px;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--text-color, #333);
  font-size: 14px;
}

.form-input,
.form-select {
  width: 100%;
  padding: 10px 14px;
  border: 1px solid var(--border-color, #d1d5db);
  border-radius: 8px;
  font-size: 15px;
  color: var(--text-color, #333);
  background: var(--bg-color, #fff);
  transition: all 0.2s;
}

.form-input:focus,
.form-select:focus {
  outline: none;
  border-color: var(--primary-color, #3b82f6);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
}

.form-checkbox {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.form-hint {
  margin-top: 12px;
  font-size: 13px;
  color: var(--text-secondary, #6b7280);
  line-height: 1.5;
}

.btn {
  padding: 10px 24px;
  border: none;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-primary {
  background: var(--primary-color, #3b82f6);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: var(--primary-dark, #2563eb);
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-secondary {
  background: var(--bg-secondary, #f3f4f6);
  color: var(--text-color, #333);
}

.btn-secondary:hover {
  background: var(--border-color, #e5e7eb);
}

.btn-warning {
  background: #f59e0b;
  color: white;
}

.btn-warning:hover {
  background: #d97706;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn-danger:hover {
  background: #dc2626;
}

.btn-sm {
  padding: 6px 14px;
  font-size: 13px;
}

.sessions-list {
  margin-bottom: 20px;
}

.session-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid var(--border-color, #e5e7eb);
  border-radius: 8px;
  margin-bottom: 12px;
}

.session-info {
  flex: 1;
}

.session-device {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.session-device strong {
  color: var(--text-color, #333);
}

.session-details {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: var(--text-secondary, #6b7280);
}

.danger-zone {
  border: 2px solid #fca5a5;
  background: #fef2f2;
}

.dark-theme .danger-zone {
  border-color: #dc2626;
  background: #450a0a;
}

.danger-actions {
  display: flex;
  gap: 12px;
}

/* 深色模式 */
.dark-theme .settings-section {
  background: #1f2937;
}

.dark-theme .info-card {
  border-color: #374151;
}

.dark-theme .info-row {
  border-bottom-color: #374151;
}

.dark-theme .form-input,
.dark-theme .form-select {
  background: #111827;
  border-color: #374151;
  color: #e5e7eb;
}

.dark-theme .badge-user {
  background: #374151;
  color: #e5e7eb;
}

.dark-theme .btn-secondary {
  background: #374151;
  color: #e5e7eb;
}

.dark-theme .btn-secondary:hover {
  background: #4b5563;
}

.dark-theme .session-card {
  border-color: #374151;
}

/* 响应式 */
@media (max-width: 768px) {
  .settings-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .settings-form {
    max-width: 100%;
  }
  
  .session-card {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .session-details {
    flex-direction: column;
    gap: 8px;
  }
}
</style>


